<template>
  <div>
    <el-dialog
      title="网站Feed抓取配置"
      :visible.sync="thisdialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          :disabled="listLoading"
          @click="handleAction('create', '添加配置')"
        >添加分页
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @sort-change="handleSort"
      >

        <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />

        <el-table-column align="center" label="域名" prop="FeedConfig__website__domain" />
        <el-table-column align="center" label="子分类" prop="oneSKU" width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_sub_feed"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <div v-if="scope.row.is_sub_feed">
              <p v-if="scope.row.sub_feed_custom_label_0 !== ''">custom_label_0:{{ scope.row.sub_feed_custom_label_0 }}</p>
              <p v-if="scope.row.sub_feed_custom_label_1 !== ''">custom_label_1:{{ scope.row.sub_feed_custom_label_1 }}</p>
              <p v-if="scope.row.sub_feed_custom_label_2 !== ''">custom_label_2:{{ scope.row.sub_feed_custom_label_2 }}</p>
              <p v-if="scope.row.sub_feed_custom_label_3 !== ''">custom_label_3:{{ scope.row.sub_feed_custom_label_3 }}</p>
              <p v-if="scope.row.sub_feed_custom_label_4 !== ''">custom_label_4:{{ scope.row.sub_feed_custom_label_4 }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单SKU" prop="oneSKU">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.oneSKU"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleChangeOneSKU(scope.row)"
            />
          </template>
        </el-table-column>

        <el-table-column align="center" label="分页大小" prop="page_size" sortable="custom">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handleGetRecords(scope.row)">{{ scope.row.page_size }}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="Feed文件" prop="xml_link">
          <template slot-scope="scope">
            <a v-if="scope.row.xml_link" :href="scope.row.xml_link" target="_blank">新增{{ scope.row.new }}个产品,点击下载</a>
            <p v-else>未生成</p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="开始生成Feed文件" prop="enable">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleAction('enable', scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="生成状态" prop="task_status">
          <template slot-scope="scope">
            <el-dropdown size="mini" split-button :type="options[scope.row.state-1].type">
              {{ options[scope.row.state-1].label }}
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="scope.row.state != 1"
                  @click.native.stop="handleChangeState(scope.row,1)"
                >调整为生成中
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.state != 2"
                  @click.native.stop="handleChangeState(scope.row,2)"
                >调整为生成结束
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后产品ID" prop="id_ps_product" sortable="custom" />
        <el-table-column align="center" label="开始时间" prop="start_at" sortable="custom" />
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            <el-button size="mini" type="warning" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" :loading="genratexmlloading" type="success" @click="handleGenerateFeed(scope.row)">组合feed文件</el-button>
          </template>
        </el-table-column>
        `
      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />

      <el-dialog
        append-to-body
        :title="title"
        :width="width"
        :visible.sync="innerDialogVisible"
        :close-on-click-modal="false"
      >
        <el-form :model="temp" label-position="left" label-width="180px">
          <el-form-item v-if="action === 'edit' || action === 'create'" label="子 feed:">
            <el-switch
              v-model="temp.is_sub_feed"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item v-if="action === 'edit' || action === 'create'" label="分页大小:">
            <el-input-number v-model="temp.page_size" :step="100" />
            <el-tag type="danger">请注意!bigcommerce/woocommerece网站只能添加size为100的分页</el-tag>
          </el-form-item>
          <el-form-item v-if="action === 'edit' || action === 'create'" label="单个SKU:">
            <el-switch
              v-model="temp.oneSKU"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item v-if="temp.is_sub_feed" label="custome label 0(订单数):">
            <el-input v-model="temp.sub_feed_custom_label_0" />
          </el-form-item>
          <el-form-item v-if="temp.is_sub_feed" label="custome label 1:">
            <el-input v-model="temp.sub_feed_custom_label_1" />
          </el-form-item>
          <el-form-item v-if="temp.is_sub_feed" label="custome label 2(关键词):">
            <el-input v-model="temp.sub_feed_custom_label_2" />
          </el-form-item>
          <el-form-item v-if="temp.is_sub_feed" label="custome label 3(目录id):">
            <el-input v-model="temp.sub_feed_custom_label_3" />
          </el-form-item>
          <el-form-item v-if="temp.is_sub_feed" label="custome label 4:">
            <el-input v-model="temp.sub_feed_custom_label_4" />
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerDialogVisible = false">取 消</el-button>
          <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
    <feedgeneraterecord
      :dialog-visuable="feedGenerateRecordVisuable"
      :feedpagesize_id="feedpagesize_id"
      @closeFeedPageDialog="feedGenerateRecordVisuable=false"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/feed/feedpagesize'
// import { Get as GetWebsite } from '@/api/erp/elicink/website'
import { GenerateFeed } from '@/api/feed/feedapi'
import feedgeneraterecord from '@/views/feed/elements/feedgeneraterecord'

import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Feedpagesize',
  components: { feedgeneraterecord },
  props: ['dialogVisuable', 'feedconfig_id'],
  data() {
    return {
      genratexmlloading: false,
      data: [],
      listLoading: true,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      thisdialogVisible: false,
      title: '',
      temp: {
        feedconfig_id: '',
        page_size: 500,
        oneSKU: true,
        is_sub_feed: false,
        sub_feed_custom_label_0: '',
        sub_feed_custom_label_1: '',
        sub_feed_custom_label_2: '',
        sub_feed_custom_label_3: '',
        sub_feed_custom_label_4: ''
      },
      width: '',
      websites: [],
      innerDialogVisible: false,
      feedGenerateRecordVisuable: false,
      feedpagesize_id: '',
      FeedConfig__website__type: '',
      options: [
        {
          value: 1,
          type: 'danger',
          label: '正在生成中'
        },
        {
          value: 2,
          type: 'success',
          label: '已经停止'
        },
        {
          value: 3,
          type: 'warning',
          label: '运行错误'
        },
        {
          value: 4,
          type: 'primary',
          label: '未开始'
        }
      ]
    }
  },
  watch: {
    dialogVisuable(v) {
      this.thisdialogVisible = v
    },
    feedconfig_id(v) {
      if (v) {
        this.getList()
      }
    }
  },
  methods: {
    resetTemp() {
      this.temp = {
        feedconfig_id: this.feedconfig_id,
        page_size: 500,
        oneSKU: true,
        is_sub_feed: false,
        sub_feed_custom_label_0: '',
        sub_feed_custom_label_1: '',
        sub_feed_custom_label_2: '',
        sub_feed_custom_label_3: '',
        sub_feed_custom_label_4: ''
      }
    },
    getList() {
      // GetWebsite().then(response => {
      //   this.websites = response.data.data;
      // })
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        feedconfig_id: this.feedconfig_id,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleGetRecords(row) {
      this.feedGenerateRecordVisuable = true
      this.feedpagesize_id = row.id
    },
    handleGenerateFeed(row) {
      this.genratexmlloading = true
      GenerateFeed(row.id, null)
        .then(response => {
          const h = this.$createElement
          this.$notify({
            title: '生成Feed文件',
            message: h('i', { style: 'color: teal' }, '发送命令成功')
          })
          this.genratexmlloading = false
        }).catch(err => {
          console.log(err)
          this.genratexmlloading = false
        })
    },
    handleChangeOneSKU(row) {
      Put(row.id, {
        oneSKU: row.oneSKU
      }).then((response) => {
        this.notify('更新成功')
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row.page_size
          this.resetTemp()
          if (row.FeedConfig__website__type !== 'PrestaShop') {
            this.temp.page_size = 100
          }
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.page_size}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.page_size}配置`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'enable':
          this.width = '50%'
          if (row.enable) {
            this.title = `开始生成page size为${row.page_size}的feed文件`
          } else {
            this.title = `结束生成page size为${row.page_size}的feed文件`
          }
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (this.feedconfig_id === '') {
            alert('错误，没有指定配置')
            return
          }
          if (!_data.page_size === 0) {
            alert('page size 不能为0')
            return
          }
          if (_data.is_sub_feed) {
            if (_data.sub_feed_custom_label_0 === '' && _data.sub_feed_custom_label_1 === '' && _data.sub_feed_custom_label_2 === '' && _data.sub_feed_custom_label_3 === '' && _data.sub_feed_custom_label_4 === '') {
              this.$message.error('子分类必须填写至少一个custome label')
              return
            }
          }
          _data.feedconfig_id = this.feedconfig_id
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case 'enable':
          Put(_data.id, {
            enable: _data.enable,
            oneSKU: _data.oneSKU,
            feedconfig_id: this.feedconfig_id
          }).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
        case 'edit':
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleChangeState(row, state) {
      Put(row.id, {
        state: state
      }).then((response) => {
        this.$emit('reload')
        this.getList()
        this.notify('更新成功')
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeFeedPageDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 168px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }
</style>

